package com.sinog.biz.schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sinog.biz.BizApplication;
import com.sinog.biz.config.ThreadPoolConfig;
import com.sinog.biz.service.api.DataTransmissionService;
import com.sinog.biz.util.DataSourceCheckUtils;
import com.sinog.core.domain.PrisonerFx;
import com.sinog.core.domain.PrisonerMain;
import com.sinog.core.domain.PrisonerSr;
import com.sinog.core.domain.PrisonerZn;
import com.sinog.core.domain.UserInterFaceEntity;
import com.sinog.core.model.MultimediaInfo;
import com.sinog.core.util.Hex;
import com.sinog.core.utilbean.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Pattern;

/**
 * @desc 预安置人员数据录入，方式2：中间库方式 - (监狱、社区矫正、看守所) - mysql数据库版本
 * @author lzq
 * @date 2020-12-01 2:36 下午
 */
@Slf4j
@Component
@Configuration
@ConditionalOnProperty(name = "gkzx.azbj.outerInterface.db.mysql.open", havingValue = "true")
public class ShadowSchedule {

    /**
     * 数字正则
     */
    private static final Pattern PATTERN = Pattern.compile("\\d{9}");
    /**
     * 中间库数据源
     */
    private JdbcTemplate shadowJdbcTemplate;
    /**
     * 安置帮教库数据源
     */
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DataTransmissionService dataTransmissionService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ThreadPoolConfig threadPoolConfig;

    /**
     * 定时从中间库拉取数据保存到本地，生产具体频率根据情况决定。本地测试每分钟执行一次：0 0/1 * * * ?
     */
    @Scheduled(cron = "${gkzx.azbj.outerInterface.db.mysql.cron}")
    private void predictWarningShadowTask() {
        log.info("\n>>>>>>>>>>>starting......从中间库同步预安置人员数据<<<<<<<<<<");
        ApplicationContext applicationContext = BizApplication.applicationContext;
        if(!ObjectUtils.allNotNull(shadowJdbcTemplate)) {
            shadowJdbcTemplate = (JdbcTemplate)applicationContext.getBean("shadowJdbcTemplate");
        }
        if(!ObjectUtils.allNotNull(jdbcTemplate)) {
            jdbcTemplate = (JdbcTemplate)applicationContext.getBean("jdbcTemplate");
        }
        //检测全部数据源是否可用
        boolean allRunning = DataSourceCheckUtils.checkRunningStatus(shadowJdbcTemplate,jdbcTemplate);
        if(true){
            //1、执行sql：查询---> 中间库prisoner_main表，并且状态是0的数据，排除犯罪编号重复的数据，一次取500条。
            String mainSql = "SELECT * FROM prisoner_main WHERE state='0' " + "AND pri_num NOT IN (SELECT pri_num FROM prisoner_main WHERE pri_num IS NOT NULL GROUP BY pri_num HAVING COUNT(1)>1) LIMIT 0,500";
            String delSql = "SELECT * FROM prisoner_main WHERE state='3'";
            List<Map<String,Object>> mainLists = shadowJdbcTemplate.queryForList(mainSql);
            List<Map<String,Object>> delLists = shadowJdbcTemplate.queryForList(delSql);
            Date date = new Date();
            //2、遍历每一条主表数据，并且根据【对方的犯罪编号】查询出相关的服刑表、社会关系表、子女表、多媒体信息表
            CountDownLatch countDownLatch = new CountDownLatch(mainLists.size());
            for(Map<String,Object> mainMaps : mainLists) {
                threadPoolConfig.taskExecutor().execute(() -> {
                    log.error("线程:{},开始异步处理:{}",Thread.currentThread().getName(),mainMaps.get("p_name"));
                    //把字符串类型的value为null的置为""，避免后面抱错
                    for(String key : mainMaps.keySet()) {
                        Object value = mainMaps.get(key);
                        if(ObjectUtils.allNull(value) && (value instanceof String)) {
                            mainMaps.put(key,"");
                        }
                    }
                    //3.1、定义PrisonerMain
                    PrisonerMain prisonerMain = new PrisonerMain();
                    //3.2、取出map中prisonerMain属性
                    //前置机犯罪编号(对方)，用于查询子表，更新主表及子表及新增log日志表
                    String prinum = (String)mainMaps.get("pri_num");
                    String crid = (String)mainMaps.get("crid");
                    //安置帮教犯罪编号，用于判断是更新还是新增
                    String azbjPrinum = (String)mainMaps.get("azbj_prinum");
                    //接口账号，用于鉴权，区分该条数据属于哪个监狱
                    String account = (String)mainMaps.get("account");
                    String pname = (String)mainMaps.get("p_name");
                    String usedname = (String)mainMaps.get("used_name");
                    String sex = (String)mainMaps.get("sex");
                    //之前对接黑龙江未按照安置帮教传递，做过处理(可以去掉)
                    String nationality = (String)mainMaps.get("nationality");
                    if(null != nationality && 1 == nationality.length()) {
                        nationality = "0" + nationality;
                    }
                    String idType = (String)mainMaps.get("idType");
                    String idnum = (String)mainMaps.get("id_num");
                    Date age = (Date)mainMaps.get("age");
                    String education = (String)mainMaps.get("education");
                    Date addtime = (Date)mainMaps.get("addtime");
                    String priAddr = (String)mainMaps.get("pri_addr");
                    String nativepro = (String)mainMaps.get("nativepro");
                    String nativecity = (String)mainMaps.get("nativecity");
                    String nativecou = (String)mainMaps.get("nativecou");
                    String nativevill = (String)mainMaps.get("nativevill");
                    //之前黑龙江nativevill传递中文，做过处理(可以去掉)
                    if(!StringUtils.isEmpty(nativevill) && !PATTERN.matcher(nativevill).matches()) {
                        nativevill = "";
                    }
                    String nativenum = (String)mainMaps.get("nativenum");
                    String placepro = (String)mainMaps.get("placepro");
                    String placecity = (String)mainMaps.get("placecity");
                    String placecou = (String)mainMaps.get("placecou");
                    String placevill = (String)mainMaps.get("placevill");
                    if(!StringUtils.isEmpty(placevill) && !PATTERN.matcher(placevill).matches()) {
                        placevill = "";
                    }
                    String placenum = (String)mainMaps.get("placenum");
                    String arrestpro = (String)mainMaps.get("arrestpro");
                    String arrestcity = (String)mainMaps.get("arrestcity");
                    String arrestcou = (String)mainMaps.get("arrestcou");
                    String arrestvill = (String)mainMaps.get("arrestvill");
                    if(!StringUtils.isEmpty(arrestvill) && !PATTERN.matcher(arrestvill).matches()) {
                        arrestvill = "";
                    }
                    String arrestnum = (String)mainMaps.get("arrestnum");
                    String investigatepro = (String)mainMaps.get("investigate_pro");
                    String investigatecity = (String)mainMaps.get("investigate_city");
                    String investigatecou = (String)mainMaps.get("investigate_cou");
                    String investigatevill = (String)mainMaps.get("investigate_vill");
                    if(!StringUtils.isEmpty(investigatevill) && !PATTERN.matcher(investigatevill).matches()) {
                        investigatevill = "";
                    }
                    String investigatenum = (String)mainMaps.get("investigate_num");
                    //3.3、封装实体类prisonerMain
                    prisonerMain.setPriNum(azbjPrinum);
                    prisonerMain.setPName(pname);
                    prisonerMain.setUsedName(usedname);
                    prisonerMain.setSex(sex);
                    prisonerMain.setNationality(nationality);
                    prisonerMain.setIdType(idType);
                    prisonerMain.setIdNum(idnum);
                    prisonerMain.setAge(age);
                    prisonerMain.setEducation(education);
                    prisonerMain.setAddtime(addtime);
                    prisonerMain.setPriAddr(priAddr);
                    prisonerMain.setNativepro(nativepro);
                    prisonerMain.setNativecity(nativecity);
                    prisonerMain.setNativecou(nativecou);
                    prisonerMain.setNativevill(nativevill);
                    prisonerMain.setNativenum(nativenum);
                    prisonerMain.setPlacepro(placepro);
                    prisonerMain.setPlacecity(placecity);
                    prisonerMain.setPlacecou(placecou);
                    prisonerMain.setPlacevill(placevill);
                    prisonerMain.setPlacenum(placenum);
                    prisonerMain.setArrestpro(arrestpro);
                    prisonerMain.setArrestcity(arrestcity);
                    prisonerMain.setArrestcou(arrestcou);
                    prisonerMain.setArrestvill(arrestvill);
                    prisonerMain.setArrestnum(arrestnum);
                    prisonerMain.setInvestigatePro(investigatepro);
                    prisonerMain.setInvestigateCity(investigatecity);
                    prisonerMain.setInvestigateCou(investigatecou);
                    prisonerMain.setInvestigateVill(investigatevill);
                    prisonerMain.setInvestigateNum(investigatenum);
                    prisonerMain.setUpdateUser(account);
                    prisonerMain.setUpdateTime(date);
                    //3.4、执行sql：根据【对方犯罪编号】查询---> 中间库prisoner_fx数据
                    String fxSql = "select * from prisoner_fx where pri_num='" + prinum + "'";
                    List<Map<String,Object>> fxLists = shadowJdbcTemplate.queryForList(fxSql);
                    //3.5、处理PrisonerFx
                    PrisonerFx prisonerFx = null;
                    //如果服刑信息为空，则返回错误
                    if(fxLists.isEmpty()) {
                        String sql5 = "update prisoner_main set state='2' where pri_num='" + prinum + "'";
                        String sb = "INSERT INTO `prisoner_middle_log`(`pri_num`, `code`, `create_time`, `update_time`,`crid`) ";
                        StringBuilder sql10 = new StringBuilder(sb);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String format = simpleDateFormat.format(date);
                        //服刑表信息不能为空
                        String code = "999991";
                        sql10.append("values (").append("'").append(prinum).append("','").append(code).append("','")
                             .append(format).append("',").append("'").append(format).append("','").append(crid)
                             .append("')");
                        shadowJdbcTemplate.execute(sql5);
                        shadowJdbcTemplate.execute(sql10.toString());
                        countDownLatch.countDown();
                        return;
                    }
                    for(int j = 0; j < fxLists.size(); j++) {
                        prisonerFx = new PrisonerFx();
                        //3.5.1 取出map中prisonerFx属性
                        Map<String,Object> fxMaps = fxLists.get(j);
                        for(String key : fxMaps.keySet()) {
                            Object value = mainMaps.get(key);
                            if(ObjectUtils.allNull(value)) {
                                mainMaps.put(key,"");
                            }
                        }
                        String critype = (String)fxMaps.get("Critype");
                        String precri = (String)fxMaps.get("Precri");
                        String addpenalty = (String)fxMaps.get("Addpenalty");
                        String jinengtype = (String)fxMaps.get("jinengtype");
                        String pritime = (String)fxMaps.get("Pritime");
                        String arrjg = (String)fxMaps.get("arr_jg");
                        Date pribegin = (Date)fxMaps.get("Pri_begin");
                        Date pristop = (Date)fxMaps.get("Pri_stop");
                        String aftype = (String)fxMaps.get("Aftype");
                        String bqzy = (String)fxMaps.get("bqzy");
                        String fzlx = (String)fxMaps.get("fzlx");
                        String canji = (String)fxMaps.get("canji");
                        //3.5.2 封装实体类prisonerFx
                        prisonerFx.setCritype(critype);
                        prisonerFx.setPrecri(precri);
                        prisonerFx.setAddpenalty(addpenalty);
                        prisonerFx.setJinengtype(jinengtype);
                        prisonerFx.setPritime(pritime);
                        prisonerFx.setArrJg(arrjg);
                        prisonerFx.setPriBegin(pribegin);
                        prisonerFx.setPriStop(pristop);
                        prisonerFx.setAftype(aftype);
                        prisonerFx.setBqzy(bqzy);
                        prisonerFx.setCanji(canji);
                        prisonerFx.setUpdateUser(account);
                        prisonerFx.setUpdateTime(date);
                        //3.5.3 处理犯罪类型
                        if(!StringUtils.isEmpty(critype) && StringUtils.isEmpty(fzlx)) {
                            String[] critypes = critype.split(",");
                            List<String> fzlxs = new ArrayList<>(16);
                            for(String c : critypes) {
                                //根据罪名查询对应的犯罪类型
                                String fzlxTemp = (String)stringRedisTemplate.opsForHash().get("critypeAndFzlx",c);
                                if(StringUtils.isBlank(fzlxTemp)) {
                                    fzlxTemp = c;
                                }
                                if(!fzlxs.contains(fzlxTemp)) {
                                    fzlxs.add(fzlxTemp);
                                }
                            }
                            String temp = "";
                            for(String f : fzlxs) {
                                if(!StringUtils.isEmpty(temp)) {
                                    temp = new StringBuilder(16).append(temp).append(",").append(f).toString();
                                } else {
                                    temp = f;
                                }
                            }
                            fzlx = temp;
                        }
                        prisonerFx.setFzlx(fzlx);
                    }
                    //3.6、执行sql：根据【对方犯罪编号】查询---> 中间库prisoner_sr数据
                    String srSql = "select * from prisoner_sr where pri_num='" + prinum + "'";
                    List<Map<String,Object>> srLists = shadowJdbcTemplate.queryForList(srSql);
                    //3.7、处理PrisonerSr
                    List<PrisonerSr> prisonerSrs = new ArrayList<>(16);
                    for(Map<String,Object> srList : srLists) {
                        PrisonerSr prisonerSr = new PrisonerSr();
                        //3.7.1 取出map中PrisonerSr属性
                        Map<String,Object> srMaps = srList;
                        for(String key : srMaps.keySet()) {
                            Object value = mainMaps.get(key);
                            if(ObjectUtils.allNull(value)) {
                                mainMaps.put(key,"");
                            }
                        }
                        String thename = (String)srMaps.get("thename");
                        String relation = (String)srMaps.get("relation");
                        Date srage = (Date)srMaps.get("age");
                        String danwei = (String)srMaps.get("danwei");
                        String tel = (String)srMaps.get("tel");
                        String mobile = (String)srMaps.get("mobile");
                        String addrpro = (String)srMaps.get("addrpro");
                        String addrcity = (String)srMaps.get("addrcity");
                        String addrcou = (String)srMaps.get("addrcou");
                        String addrvil = (String)srMaps.get("addrvil");
                        if(!StringUtils.isEmpty(addrvil) && !PATTERN.matcher(addrvil).matches()) {
                            addrvil = "";
                        }
                        String addrdetail = (String)srMaps.get("addrdetail");
                        String idnumber = (String)srMaps.get("idnumber");
                        //针对黑龙江约定做特殊处理
                        if("000000000000000".equals(idnumber)) {
                            idnumber = "";
                        }
                        //3.7.2 封装实体类PrisonerSr
                        prisonerSr.setThename(thename);
                        prisonerSr.setRelation(relation);
                        prisonerSr.setAge(srage);
                        prisonerSr.setTel(!StringUtils.isEmpty(tel) && "无".equals(tel) ? "" : tel);
                        prisonerSr.setDanwei(danwei);
                        prisonerSr.setMobile(!StringUtils.isEmpty(mobile) && "无".equals(mobile) ? "" : mobile);
                        prisonerSr.setAddrpro(addrpro);
                        prisonerSr.setAddrcity(addrcity);
                        prisonerSr.setAddrcou(addrcou);
                        prisonerSr.setAddrvil(addrvil);
                        prisonerSr.setAddrdetail(addrdetail);
                        prisonerSr.setIdnumber(idnumber);
                        prisonerSr.setUpdateUser(account);
                        prisonerSr.setUpdateTime(date);
                        //3.7.3 添加PrisonerSr到list
                        prisonerSrs.add(prisonerSr);
                    }
                    //3.8、执行sql：根据【对方犯罪编号】查询---> 中间库prisoner_zn数据
                    String znSql = "select * from prisoner_zn where pri_num='" + prinum + "'";
                    List<Map<String,Object>> znLists = shadowJdbcTemplate.queryForList(znSql);
                    //3.9、处理prisonerZn
                    List<PrisonerZn> prisonerZns = new ArrayList<>(16);
                    for(Map<String,Object> znList : znLists) {
                        for(String key : znList.keySet()) {
                            Object value = mainMaps.get(key);
                            if(ObjectUtils.allNull(value)) {
                                mainMaps.put(key,"");
                            }
                        }
                        PrisonerZn prisonerZn = new PrisonerZn();
                        //3.9.1 取出map中prisonerZn属性
                        String name = (String)znList.get("name");
                        String znsex = (String)znList.get("sex");
                        Date znage = (Date)znList.get("age");
                        String jianhuren = (String)znList.get("jianhuren");
                        String kunnan = (String)znList.get("kunnan");
                        String shixue = (String)znList.get("shixue");
                        String liulang = (String)znList.get("liulang");
                        String fanzui = (String)znList.get("fanzui");
                        String znsfId = (String)znList.get("znsf_id");
                        String znnativepro = (String)znList.get("nativepro");
                        String znnativecity = (String)znList.get("nativecity");
                        String znnativecou = (String)znList.get("nativecou");
                        String znnativevill = (String)znList.get("nativevill");
                        if(!StringUtils.isEmpty(znnativevill) && !PATTERN.matcher(znnativevill).matches()) {
                            znnativevill = "";
                        }
                        String znnativenum = (String)znList.get("nativenum");
                        String znplacepro = (String)znList.get("placepro");
                        String znplacecity = (String)znList.get("placecity");
                        String znplacecou = (String)znList.get("placecou");
                        String znplacevill = (String)znList.get("placevill");
                        if(!StringUtils.isEmpty(znplacevill) && !PATTERN.matcher(znplacevill).matches()) {
                            znplacevill = "";
                        }
                        String znplacenum = (String)znList.get("placenum");
                        //3.9.2 封装实体类prisonerZn
                        prisonerZn.setName(name);
                        prisonerZn.setSex(znsex);
                        prisonerZn.setAge(znage);
                        prisonerZn.setJianhuren(jianhuren);
                        prisonerZn.setKunnan(kunnan);
                        prisonerZn.setShixue(shixue);
                        prisonerZn.setLiulang(liulang);
                        prisonerZn.setFanzui(fanzui);
                        prisonerZn.setZnsfId(znsfId);
                        prisonerZn.setNativepro(znnativepro);
                        prisonerZn.setNativecity(znnativecity);
                        prisonerZn.setNativecou(znnativecou);
                        prisonerZn.setNativevill(znnativevill);
                        prisonerZn.setNativenum(znnativenum);
                        prisonerZn.setPlacepro(znplacepro);
                        prisonerZn.setPlacecity(znplacecity);
                        prisonerZn.setPlacecou(znplacecou);
                        prisonerZn.setPlacevill(znplacevill);
                        prisonerZn.setPlacenum(znplacenum);
                        prisonerZn.setUpdateUser(account);
                        prisonerZn.setUpdateTime(date);
                        //3.9.3 添加prisonerZn到list
                        prisonerZns.add(prisonerZn);
                    }
                    //3.10、执行sql：根据【对方犯罪编号】查询---> 中间库prisoner_multimedia数据
                    String mediaSql = "select * from prisoner_multimedia where pri_num='" + prinum + "'";
                    List<Map<String,Object>> mediaLists = shadowJdbcTemplate.queryForList(mediaSql);
                    //3.11、处理multimediaInfo
                    List<MultimediaInfo> multimediaInfos = new ArrayList<>(16);
                    for(Map<String,Object> mediaList : mediaLists) {
                        MultimediaInfo multimediaInfo = new MultimediaInfo();
                        //3.11.1 取出map中multimediaInfo属性
                        Map<String,Object> mediaMaps = mediaList;
                        for(String key : mediaMaps.keySet()) {
                            Object value = mainMaps.get(key);
                            if(ObjectUtils.allNull(value)) {
                                mainMaps.put(key,"");
                            }
                        }
                        String taskId = (String)mediaMaps.get("task_id");
                        String imgstr = (String)mediaMaps.get("imgstr");
                        String filetype = (String)mediaMaps.get("filetype");
                        //3.11.2 封装实体类multimediaInfo
                        multimediaInfo.setTaskId(taskId);
                        multimediaInfo.setImgstr(imgstr);
                        multimediaInfo.setFiletype(filetype);
                        //3.11.3 添加multimediaInfo到list
                        multimediaInfos.add(multimediaInfo);
                    }
                    //3.12 查询安置帮教系统中账号信息，并根据账号信息获取接口密钥
                    String sqluser = "SELECT tu.account,tu.username,tu.orgid,tu.uid,tu.orgid as pid," + "(SELECT name from tbsys_department where id=tu.orgid) as pname," + "(SELECT name from tbsys_department where id=tu.orgid) as orgName," + "tu.departid,td.name AS departName,td.level,tu.`position`," + "tp.name AS positionName,tu.roleid,tr.name AS roleName,tu.unCheckField as unCheckField " + "FROM `tbsys_user_interface` tu " + "JOIN `tbsys_department` td ON tu.departid = td.id " + "JOIN `tbsys_position` tp ON tu.position = tp.id " + "JOIN `tbsys_role` tr ON tu.roleid = tr.id " + "WHERE tu.account= " + "'" + account + "'";
                    BeanPropertyRowMapper<UserInterFaceEntity> rowMapper = new BeanPropertyRowMapper<>(UserInterFaceEntity.class);
                    UserInterFaceEntity userInterface;
                    String signature;
                    long time = System.currentTimeMillis();
                    try {
                        userInterface = jdbcTemplate.queryForObject(sqluser,rowMapper);
                        String uid = userInterface.getUid();
                        String key = Hex.genAccessKey(uid);
                        //客户端自己生成密钥
                        signature = Hex.genSignature(key,String.valueOf(time),"/transmission/api/azbj/savePreArrangedPersonnel/");
                        //3.13、定义json对象，并添加下面节点
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("time",String.valueOf(time));
                        jsonObject.put("sign",signature);
                        jsonObject.put("PrisonerMain",prisonerMain);
                        jsonObject.put("MultimediaInfo",multimediaInfos);
                        jsonObject.put("PrisonerFx",null == prisonerFx ? "" : prisonerFx);
                        jsonObject.put("PrisonerSr",prisonerSrs);
                        jsonObject.put("PrisonerZn",prisonerZns);
                        jsonObject.put("user",userInterface);
                        //3.14、定义返回结果
                        Result result;
                        String flag;
                        //3.15、调用service入库
                        if(!StringUtils.isEmpty(azbjPrinum)) {
                            //3.15.1、更新,如果中间库主表中的安置帮教犯罪编号不为空，说明是更新
                            result = dataTransmissionService.updatePreArrangedPersonnel(JSON.toJSON(jsonObject)
                                                                                            .toString());
                            flag = "update";
                        } else {
                            //3.15.2、新增,如果中间库主表中的安置帮教犯罪编号为空，说明是新数据，或者之前尝试插入安置帮教系统失败
                            result = dataTransmissionService.savePreArrangedPersonnel(JSON.toJSON(jsonObject)
                                                                                          .toString());
                            flag = "insert";
                        }
                        //3.16、根据返回结果，进行后续处理
                        if(1 == result.getCode()) {
                            //3.16.1、成功，修改中间库主表状态state=1，更新各张表的安置帮教犯罪编号
                            String azbjPrinumSave = (String)result.getData();
                            String sql5 = "update prisoner_main set state='1',azbj_prinum='" + azbjPrinumSave + "' where pri_num='" + prinum + "'";
                            String sql6 = "update prisoner_fx set azbj_prinum='" + azbjPrinumSave + "' where pri_num='" + prinum + "'";
                            String sql7 = "update prisoner_sr set azbj_prinum='" + azbjPrinumSave + "' where pri_num='" + prinum + "'";
                            String sql8 = "update prisoner_zn set azbj_prinum='" + azbjPrinumSave + "' where pri_num='" + prinum + "'";
                            String sql9 = "update prisoner_multimedia set azbj_prinum='" + azbjPrinumSave + "' where pri_num='" + prinum + "'";
                            String sb = "INSERT INTO prisoner_middle_log (pri_num, code, create_time, update_time, azbj_prinum,crid)";
                            StringBuilder sql11 = new StringBuilder(sb);
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String format = simpleDateFormat.format(date);
                            sql11.append("values (").append("'").append(prinum).append("',").append("'0','")
                                 .append(format).append("',").append("'").append(format).append("','")
                                 .append(azbjPrinumSave).append("','").append(crid).append("')");
                            if(StringUtils.equals("insert",flag)) {
                                shadowJdbcTemplate.execute(sql6);
                                shadowJdbcTemplate.execute(sql7);
                                shadowJdbcTemplate.execute(sql8);
                                shadowJdbcTemplate.execute(sql9);
                            }
                            shadowJdbcTemplate.execute(sql5);
                            shadowJdbcTemplate.execute(sql11.toString());
                        } else if(-50009 == result.getCode()) {
                            //3.34.2、流程中不能修改信息，修改中间库主表状态state=2，把返回错误码，存储到中间库日志表
                            String sql5 = "update prisoner_main set state='3' where pri_num='" + prinum + "'";
                            shadowJdbcTemplate.execute(sql5);
                        } else {
                            //3.34.3、失败，修改中间库主表状态state=2，把返回错误码，存储到中间库日志表
                            String code = result.getData().toString();
                            String sql5 = "update prisoner_main set state='2' where pri_num='" + prinum + "'";
                            String sb = "INSERT INTO `prisoner_middle_log`(`pri_num`, `code`, `create_time`, `update_time`,`crid`) ";
                            StringBuilder sql10 = new StringBuilder(sb);
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String format = simpleDateFormat.format(date);
                            if(StringUtils.isBlank(code)) {
                                code = "999999";
                            }
                            sql10.append("values (").append("'").append(prinum).append("','").append(code).append("','")
                                 .append(format).append("',").append("'").append(format).append("','").append(crid)
                                 .append("')");
                            shadowJdbcTemplate.execute(sql5);
                            shadowJdbcTemplate.execute(sql10.toString());
                        }
                    } catch(Exception e) {
                        log.error("发生异常{}",e.getMessage());
                        //3.34.3、发生异常，修改中间库主表状态state=2，把返回错误码，存储到中间库日志表
                        String sql6 = "update prisoner_main set state='2' where pri_num='" + prinum + "'";
                        String sb = "INSERT INTO `prisoner_middle_log`(`pri_num`, `code`, `create_time`, `update_time`,`crid`) ";
                        StringBuilder sql11 = new StringBuilder(sb);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String format = simpleDateFormat.format(date);
                        sql11.append("values (").append("'").append(prinum).append("','").append("999999").append("','")
                             .append(format).append("',").append("'").append(format).append("','").append(crid)
                             .append("')");
                        shadowJdbcTemplate.execute(sql6);
                        shadowJdbcTemplate.execute(sql11.toString());
                    }
                    countDownLatch.countDown();
                });
            }

            // 调用await()方法让主线程阻塞
            try {
                countDownLatch.await();
            } catch(InterruptedException e) {
                log.error("发生异常{}",e.getMessage());
            }
            log.info("\n>>>>>>>>>>>ending......从中间库同步预安置人员数据<<<<<<<<<<");

            //遍历要删除的数据
            log.info("\n>>>>>>>>>>>starting......从中间库同步要删除的数据<<<<<<<<<<");
            for(Map<String,Object> mainMaps : delLists) {
                String prinum = (String)mainMaps.get("pri_num");
                //安置帮教犯罪编号，用于判断是更新还是新增
                String azbjPrinum = (String)mainMaps.get("azbj_prinum");
                if(StringUtils.isNotBlank(azbjPrinum)) {
                    //根据安置帮教犯罪编号查询数据是否是流程中状态
                    String sql = "select count(1) from prisoner_main where state in('0','1') and pri_num = '" + azbjPrinum + "'";
                    int count = jdbcTemplate.queryForObject(sql,Integer.class);
                    //根据安置帮教犯罪编号删除安置帮教系统中流程未开始的数据：主表、服刑表、文件表、社会关系表、子女表、状态表
                    if(0 < count) {
                        String delMain = "delete from prisoner_main where pri_num = '" + azbjPrinum + "'";
                        String delFx = "delete from prisoner_fx where pri_num = '" + azbjPrinum + "'";
                        String delSr = "delete from prisoner_sr where pri_num = '" + azbjPrinum + "'";
                        String delZn = "delete from prisoner_zn where pri_num = '" + azbjPrinum + "'";
                        String delUploadFiles = "delete from upload_appendix_file where pri_num = '" + azbjPrinum + "'";
                        String delTemp = "delete from prisave_temp where pri_num = '" + azbjPrinum + "'";
                        jdbcTemplate.execute(delMain);
                        jdbcTemplate.execute(delFx);
                        jdbcTemplate.execute(delSr);
                        jdbcTemplate.execute(delZn);
                        jdbcTemplate.execute(delUploadFiles);
                        jdbcTemplate.execute(delTemp);
                        String sql5 = "update prisoner_main set state='4',azbj_prinum='' where pri_num='" + prinum + "'";
                        String sql6 = "update prisoner_fx set azbj_prinum='' where pri_num='" + prinum + "'";
                        String sql7 = "update prisoner_sr set azbj_prinum='' where pri_num='" + prinum + "'";
                        String sql8 = "update prisoner_zn set azbj_prinum='' where pri_num='" + prinum + "'";
                        String sql9 = "update prisoner_multimedia set azbj_prinum='' where pri_num='" + prinum + "'";
                        String sql10 = "INSERT INTO prisoner_middle_log (pri_num, code, create_time, update_time, azbj_prinum,crid) " + " VALUES (prinum,'0',NOW(),NOW(),'','')";
                        shadowJdbcTemplate.execute(sql5);
                        shadowJdbcTemplate.execute(sql6);
                        shadowJdbcTemplate.execute(sql7);
                        shadowJdbcTemplate.execute(sql8);
                        shadowJdbcTemplate.execute(sql9);
                        shadowJdbcTemplate.execute(sql10);
                    } else {
                        String sql5 = "update prisoner_main set state='5' where pri_num='" + prinum + "'";
                        String sql10 = "INSERT INTO prisoner_middle_log (pri_num, code, create_time, update_time, azbj_prinum,crid) " + " values ( ''" + prinum + "','999888',now(),now(),'" + azbjPrinum + "','')";
                        shadowJdbcTemplate.execute(sql5);
                        shadowJdbcTemplate.execute(sql10);
                    }
                }
            }
            log.info("\n>>>>>>>>>>>ending......从中间库同步要删除的数据<<<<<<<<<<");
            try {
                countDownLatch.await();
            } catch(InterruptedException e) {
                log.error("发生异常{}",e.getMessage());
            }
            log.info("\n>>>>>>>>>>>ending......从中间库同步预安置人员数据<<<<<<<<<<");
        } else {
            log.error("检测到数据源不可用,中间库对接mysql版本任务失败!");
        }
    }
}